package com.jumi.microservice.wdt;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jumi.microservice.constant.afterseal.AfterSealOrderStatusEnum;
import com.jumi.microservice.dto.wdt.PushOrderRequest;
import com.jumi.microservice.dto.wdt.WdtGoodsRequest;
import com.jumi.microservice.dto.wdt.WdtOrderRequest;
import com.jumi.microservice.dto.wdt.WdtResultResponse;
import com.jumi.microservice.entity.AfterSealOrder;
import com.jumi.microservice.entity.AfterSealOrderGoods;
import com.jumi.microservice.enumerate.LogisticsStatusEnum;
import com.jumi.microservice.enumerate.SelfFlagEnum;
import com.jumi.microservice.mapper.AfterSealOrderGoodsMapper;
import com.jumi.microservice.mapper.AfterSealOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Dirk
 * @Date 2020-08-15 10:31
 */
@Service
@RefreshScope
public class WdtService {

    private static final Logger log = LoggerFactory.getLogger(WdtService.class);

    @Value("${wdt.repo:0}")
    private String wdtWarehouse;

    @Resource
    private WdtOrderClient wdtOrderClient;

    @Resource
    private AfterSealOrderMapper afterSealOrderMapper;

    @Resource
    private AfterSealOrderGoodsMapper afterSealOrderGoodsMapper;

    @Resource
    private WdtRequestConvert wdtRequestConvert;

    public WdtResultResponse pushOrder(PushOrderRequest pushOrderRequest) {
        WdtResultResponse wdtResultResponse = new WdtResultResponse();
        List<String> afterSealOrderNos = pushOrderRequest.getOrderLogisticsNos();
        List<AfterSealOrder> afterSealOrderList;
        QueryWrapper<AfterSealOrder> afterSealOrderQw = new QueryWrapper<>();
        afterSealOrderQw.eq("is_wdt_push",0);
        afterSealOrderQw.eq("order_status", AfterSealOrderStatusEnum.ORDRE_STATUS_SHIP.getCode());
        if (afterSealOrderNos != null) {
            afterSealOrderQw.in("order_no", afterSealOrderNos);
        }
//        else {
//            // 查询所有旺店通待发货包裹
//        }
        afterSealOrderList = afterSealOrderMapper.selectList(afterSealOrderQw);
        List<Integer> orderIdList = afterSealOrderList.stream().map(AfterSealOrder::getId).collect(Collectors.toList());
        if (orderIdList.isEmpty()) {
            wdtResultResponse.setPushOrderNum(0);
            return wdtResultResponse;
        }

        // 查询包裹中的所有商品
        QueryWrapper<AfterSealOrderGoods> afterSealOrderGoodsQw = new QueryWrapper<>();
        afterSealOrderGoodsQw.in("order_id", orderIdList)
                .eq("warehouse",wdtWarehouse).eq("self_flag", SelfFlagEnum.YES_SELF.getCode())
                .eq("goods_status", LogisticsStatusEnum.WAIT_SEND.getCode());
        List<AfterSealOrderGoods> afterSealOrderGoodsList = afterSealOrderGoodsMapper.selectList(afterSealOrderGoodsQw);
        Set<Integer> orderIdss = afterSealOrderGoodsList.stream().map(AfterSealOrderGoods::getOrderId).collect(Collectors.toSet());
        log.info("需要推单的包裹:[{}], 包含的商品为:[{}]", JSON.toJSONString(afterSealOrderNos), JSON.toJSONString(afterSealOrderGoodsList));
        List<Integer> orderIds = new ArrayList<>();
        // data to object
        List<WdtOrderRequest> wdtOrderRequestList = new ArrayList<>();
        afterSealOrderList = afterSealOrderList.stream().filter(o->orderIdss.contains(o.getId())).collect(Collectors.toList());
        afterSealOrderList.forEach(afterSealOrder -> {
            List<AfterSealOrderGoods> subAfterSealOrderList = afterSealOrderGoodsList.stream()
                    .filter(afterSealOrderGoods -> afterSealOrderGoods.getOrderId().equals(afterSealOrder.getId()))
                    .collect(Collectors.toList());
            if(subAfterSealOrderList.stream().map(item -> item.getGoodsWeight().multiply(new BigDecimal(item.getGoodsAmount())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(new BigDecimal(3.00))<=0){
                WdtOrderRequest wdtOrderRequest = wdtRequestConvert.wdtOrderRequestConvert(afterSealOrder);
                List<WdtGoodsRequest> wdtGoodsRequestList = wdtRequestConvert.wdtGoodsRequestsConvert(subAfterSealOrderList);
                wdtOrderRequest.setOrderList(wdtGoodsRequestList);
                wdtOrderRequestList.add(wdtOrderRequest);
                orderIds.add(afterSealOrder.getId());
            }
        });
        // push order
        int size = 100;
        for (int i = 0; i - size < wdtOrderRequestList.size(); i += size) {
            wdtOrderClient.pushOrder(wdtOrderRequestList.subList(i, Math.min(i, wdtOrderRequestList.size())));
        }
        //修改订单旺店通已推送
        UpdateWrapper<AfterSealOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",orderIds);
        AfterSealOrder afterSealOrder = new AfterSealOrder();
        afterSealOrder.setIsWdtPush((byte)1);
        afterSealOrderMapper.update(afterSealOrder,updateWrapper);
        //修改订单商品旺店通已推送
        UpdateWrapper<AfterSealOrderGoods> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.in("order_id",orderIds);
        AfterSealOrderGoods afterSealOrderGoods = new AfterSealOrderGoods();
        afterSealOrderGoodsMapper.update(afterSealOrderGoods,updateWrapper1);
        wdtResultResponse.setPushOrderNum(wdtOrderRequestList.size());
        return wdtResultResponse;
    }

//    @Scheduled(fixedDelay = 5 * 60 * 1000)
//    public void logisticsSync() {
//        wdtOrderClient.logisticsSync();
//    }
}
